import { ref } from 'vue';

import { api } from '@/service';
import { defineStore } from 'pinia';

export const useMenuStore = defineStore('menu', () => {
	const currentUserInfo = ref<UniCloud.CurrentUserInfo>(uniCloud.getCurrentUserInfo());

	const menuList = ref<IMenu[]>(uni.getStorageSync('opendb-admin-menus') || []);

	const treeMenu = computed(() => {
		const { permission, role } = currentUserInfo.value;

		const perMenu =
			menuList.value
				?.filter((item) => {
					if (role.includes('admin')) {
						return true;
					}

					if (item.menu_id === 'index') {
						return true;
					}

					if (item.permission.some((p) => permission.includes(p))) {
						return true;
					}

					if (!item.url && menuList.value.filter((m) => m.parent_id === item.menu_id).some((m) => m.permission.some((p) => permission.includes(p)))) {
						return true;
					}
				})
				.map((item) => ({
					label: item.name,
					key: item.menu_id,
					parentId: item.parent_id,
					url: item.url,
				})) ?? [];

		return handleTree({ data: perMenu, id: 'key', parentId: 'parentId' });
	});

	const getMenuList = async () => {
		try {
			const data = await api.menu.getEnableMenu();
			menuList.value = data ?? [];
			uni.setStorageSync('opendb-admin-menus', menuList.value);
		} catch (error) {
			console.error(error);
		}
	};

	uni.$on('uni-id-pages-login-success', () => {
		currentUserInfo.value = uniCloud.getCurrentUserInfo();
	});

	return {
		menuList,
		treeMenu,
		getMenuList,
	};
});

export const useMenuStoreHook = () => {
	return useMenuStore(store);
};
